package org.kingtop.shiro.quartz;

import java.util.Map;
import java.util.Set;

import org.kingtop.cache.IRedisTemplate;
import org.kingtop.shiro.cache.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用于定时检查{@link RedisCache}类中缓存数据是否过期，删除过期部分的数据
 * @author 陈金波
 * @date   2018年1月17日 下午8:21:02    
 * @Copyright: 2018 chen jinbo. All rights reserved.
 */
public class RedisCacheCheckJobTask {
	
	private Logger logger = LoggerFactory.getLogger(RedisCacheCheckJobTask.class);

	private IRedisTemplate redisTemplate;
	
	/**
	 * 检查过期数据并删除
	 * @author 陈金波  
	 * @date   2018年1月17日 下午8:22:55  
	 * @return void
	 */
	public void checkOverTime(){
		if(redisTemplate == null) {
			throw new IllegalArgumentException(getClass().getName() + " redisTemplate is required");
		}
		Map<String, String> redisMap = this.redisTemplate.hgetAll(RedisCache.REDIS_CACHE_SET_PREFIX_EXPIRE);
		for (Map.Entry<String, String> item : redisMap.entrySet()) {
			long expert = Long.parseLong(item.getValue());
			if(expert > 0) {
				String keyPrefix = item.getKey();
				long currentTimeMillis = System.currentTimeMillis();
				long overTimeMillis = currentTimeMillis - expert * 1000;
				//获取过期的key
				Set<String> keys = this.redisTemplate.zrangeByScore(keyPrefix + RedisCache.ORDER_PREFIX, 0, overTimeMillis);
				if(keys.size() >0) {
					//移除排序中的这些数据
					long count = this.redisTemplate.zremrangeByScore(keyPrefix + RedisCache.ORDER_PREFIX, 0, overTimeMillis);
					logger.info("正在删除{}，其中确定删除{}条", keys.toString(), count);
					//删除真是的数据
					this.redisTemplate.hdel(keyPrefix, keys.toArray(new String[] {}));
				}
			}
		}
	}

	/**
	 * @return the redisTemplate
	 */
	public IRedisTemplate getRedisTemplate() {
		return redisTemplate;
	}

	/**
	 * @param redisTemplate the redisTemplate to set
	 */
	public void setRedisTemplate(IRedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
}
